<template>
    <div>
      <el-dialog v-model="form.dialogFormVisible">
      <div class="header">{{form.title}}</div>
      <el-form :model="form">
        <el-form-item>
          <el-input
            @blur="blurFun"
            v-model="form.deptName1"
            placeholder="请输入新部门名称"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
           <el-autocomplete
              clearable 
              v-model="form.userId"
              :fetch-suggestions="querySearch"
              placeholder="搜索查找部门领导"
              @select="handleSelect"
            ></el-autocomplete>
        </el-form-item>
        <el-form-item>
          <template #default>
            <el-space wrap>
              <el-select v-model="form.deptName" placeholder="--部门--">
                <el-option @click="seletFun(v)" v-for="(v,i) in depan" :key="i" :label="v.deptName" :value="v.id"></el-option>
              </el-select>
            </el-space>
            <el-select v-model="form.nickName" :disabled="disbaled" multiple placeholder="请选择添加部门成员">
              <el-option @click="seletFun1(v)" v-for="(v,i) in depanlist" :key="i" :label="v.nickName" :value="v._id"></el-option>
            </el-select>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="form.dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="form.title==='添加部门'?addOkFun():addOkFun1()">确 定</el-button>
        </span>
      </template> 
    </el-dialog>
    </div>
</template>
<script>
import {cheng,addDert,list,depentlist,editDert,elmit} from '../api/user'
import { reactive, toRefs,ref,onMounted,watch } from "vue";  
import { ElMessage } from 'element-plus'
export default {
    data() {
        return {
        }
    },
    props:{
      form:Object
    },
    setup(props,{emit}) {
    const restaurants = ref([]);
    const {form} = toRefs(props)
    const depan = reactive([])
    const depanlist = reactive([])
    const page = ref(1)
    const limit = ref(5)
    const name = ref('')
    const uid= ref('')
    const disbaled = ref(true)
    const state=reactive([
      {
        value:'0',
        label:'离职'
      },{
        value:'1',
        label:'在职'
      },{
        value:'2',
        label:'试用期'
      }
    ])
    const loadAll = () => {
      let arr=[]
      // 搜索部门领导
      list({page:page.value,limit:limit.value,userName:name.value}).then((res)=>{
        if(res.status==200){
          res.data.forEach((v,i)=>{
            arr.push({
              value:v.userName,
              id:v._id
            })
          })
        }
      })
      return arr
    }
    const querySearch = (queryString, cb) => {
      var results = queryString
        ? restaurants.value.filter(createFilter(queryString))
        : restaurants.value;
      // 调用 callback 返回建议列表的数据
      cb(results);
    };
    const createFilter = (queryString) => {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    };
    const handleSelect = (item) => {
      uid.value = item.value;
      form.value.userId=item.id
    };
    // 失焦
    const blurFun=()=>{
      if(form.value.title=='添加部门'){
        depentlist({page:page.value,limit:limit.value,userName:name.value}).then((res)=>{
        if(res.status==200){
          res.data.forEach((v,i)=>{
            if(v.deptName==form.value.deptName){
              ElMessage.error({
              message:'部门重复,请重新输入',
              type:'error',
              duration:1000
            });
            form.value.deptName=''
            }
          })
        }
      })
      }
    }
      // 下拉选择部门
    const seletFun=(val)=>{
      
      depanlist.splice(0,depanlist.length)
      disbaled.value = false
      depan.forEach(v=>{
        if (val.id == v.id) {
          v.children.forEach(z => {
            depanlist.push(z)
          })
        }
      })
      // form.deptName=val.deptName
    }
    //下拉选择部门成员
    const seletFun1=(val)=>{
      form.nickName=val.value
    }
    // 添加遮罩层确定按钮
    const addOkFun=()=>{
      console.log(form.value);

      let Promise1 = new Promise((resolve,reject) => {
        addDert({deptName:form.value.deptName1,userId:form.value.userId}).then((res)=>{
          if(res.status==200){
            depentlist().then(res1 => {
              if (res1.status == 200) {
                resolve(res1.data)
              }
            },err => {
              console.log(err);
            })
          }else{
            // ElMessage.success({
            //   message: '部门添加成功',
            //   type: 'success',
            //   duration:1000
            // });
            // form.value.dialogFormVisible=false
            // emit('formFun', form.value.dialogFormVisible)
            // ElMessage.error({
            //   message:'部门添加失败',
            //   type:'error',
            //   duration:1000
            // });
            // form.value.dialogFormVisible=false
            reject(res.data.msg)
          }
        })
      })

      Promise1.then(res => {
        return res
      },err => {
        console.log(err);
      })
      .then(res => {
        let ids;
        res.forEach(v => {
          if (form.value.deptName1 == v.deptName) {
            ids = v.id
          }
        })
        form.value.nickName.forEach(v => {
          elmit({id:v,deptId:ids}).then(res => {
            if (res.status == 200){
              console.log(res.data);
            }
          },err => {
            console.log(err);
          })
        })
      },err => {
        console.log(err);
      })
    }
    // 下拉部门
    cheng().then((res)=>{
      if(res.status==200){
        res.data.forEach((v,i) => {
          depan.push(v)
        });
      }
    })
    const seletFun2=(val)=>{
      form.state=val.value
    }
    // 获取部门成员数据
    // list({page:page.value,limit:limit.value,userName:name.value}).then((res)=>{
    //   if(res.status==200){
    //     res.data.forEach((v,i) => {
    //       depanlist.push(v)
    //     });
    //   }
    // })
    onMounted(() => {
      restaurants.value = loadAll();
    });
      // 编辑确定按钮
    const addOkFun1=()=>{
        // let arr={...form}
        // elmit({
        //   id:arr._id,
        //   mobile:arr.mobile,
        //   userEmail:arr.userEmail,
        //   userName:arr.userName,
        //   nickName:arr.nickName,
        //   state:arr.state,
        //   deptId:arr.deptId,
        //   role:1,
        //   userPwd:arr.userPwd,
        //   job:arr.job
        // }).then((res)=>{
        //   if(res.status==200){
        //     ElMessage.success({
        //       message: '编辑成功',
        //       type: 'success',
        //       duration:1000
        //     });
        //     form.dialogFormVisible=false
        //     listFun()
        //   }else{
        //     ElMessage.error({
        //       message:'编辑失败',
        //       type:'error',
        //       duration:1000
        //     });
        //     form.dialogFormVisible=false
        //   }
        // })
      }
      return {
        form,
        state,
        blurFun,
        loadAll,
        depan,
        uid,
        depanlist,
        seletFun,
        seletFun1,
        seletFun2,
        addOkFun,
        addOkFun1,
        querySearch,
        handleSelect,
        restaurants,
        disbaled
      }
    },
    methods: {
    },
}
</script>

<style lang="scss" scoped>
@import '../style/scss.scss';
.header {
    width: 100%;
    height: 30px;
    border-left: $border-left;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
</style>